package cn.jbolt.core.gen;

import cn.jbolt.core.consts.JBoltConst;
import cn.jbolt.core.enjoy.directive.ColumnTypeToDirective;
import cn.jbolt.core.util.JBoltConsoleUtil;
import cn.jbolt.core.util.JBoltRemarkUtil;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.generator.BaseModelGenerator;
import com.jfinal.plugin.activerecord.generator.TableMeta;

import java.util.List;

/**
 * Base model 生成器
 */
public class JBoltBaseModelGenerator extends BaseModelGenerator {
	private String dataSourceConfigName;
	public JBoltBaseModelGenerator(String dataSourceConfigName,String baseModelPackageName, String baseModelOutputDir) {
		super(baseModelPackageName, baseModelOutputDir);
		getterTypeMap.put("java.lang.Boolean", "getBoolean");
		getterTypeMap.put("java.sql.Time", "getTime");
		getterTypeMap.put("java.util.Date", "getDate");
		this.dataSourceConfigName = dataSourceConfigName;
	}

	@Override
	protected void initEngine() {
		super.initEngine();
//		engine.setStaticFieldExpression(true);
//		engine.setStaticMethodExpression(true);
		engine.addSharedMethod(new JBoltRemarkUtil());
		engine.addDirective("columnTypeTo", ColumnTypeToDirective.class);
		engine.setDevMode(true);
		setTemplate("/gentpl/base_model_template.jf");
	}

	@Override
	public void generate(List<TableMeta> tableMetas) {
		JBoltConsoleUtil.printMessage("-------------------------Base Model-------------------------");
		JBoltConsoleUtil.printMessageWithDate(" Generate Base Model :Starting ...");
		JBoltConsoleUtil.printMessageWithDate(" Base Model Output Dir: " + baseModelOutputDir);
		JBoltConsoleUtil.printMessageWithDate(" JBolt Base Model Generator is Working...");
		for (TableMeta tableMeta : tableMetas) {
			genBaseModelContent(tableMeta);
		}
		writeToFile(tableMetas);
		JBoltConsoleUtil.printMessageWithDate(" Generate Base Model :Done ...");
	}

	@Override
	protected void genBaseModelContent(TableMeta tableMeta) {
		JBoltConsoleUtil
				.printMessageWithDate(" Generate Base Model:" + baseModelPackageName + "." + tableMeta.baseModelName);
		Kv data = Kv.by("baseModelPackageName", baseModelPackageName);
		data.set("generateChainSetter", generateChainSetter);
		data.set("tableMeta", tableMeta);
		data.set("charToBoolean", JBoltProjectGenConfig.charToBoolean);
		data.set("dataSourceConfigName", dataSourceConfigName);
		data.set("genColConstant", JBoltProjectGenConfig.genColConstant);
		data.set("genColConstantToUpperCase", JBoltProjectGenConfig.genColConstantToUpperCase);
		data.set("extendsJBoltBaseModel", JBoltProjectGenConfig.baseModelExtendsJBoltBaseModel);
		data.set("javaTypeMap", JBoltConst.JAVA_TYPE_MAP);
		tableMeta.columnMetas.forEach(cm -> {
			if ("Long".equals(JBoltConst.JAVA_TYPE_MAP.get(cm.javaType))) {
				data.set("needJSONField", true);
				return;
			}
		});
		tableMeta.baseModelContent = engine.getTemplate(template).renderToString(data);
	}

}
